<?php
namespace Api\Controller;
class IndexController extends CommonController {
    private $action_name = ACTION_NAME;
    private $InsertStatus;
    private $transactionData = array();
    private $CreateOrder = array();
    private $channelInfo = array(); // 渠道与商户号PayName信息
    private $payData = array(); // 预支付调用信息
    public function _initialize(){
        $this->OrderInit(); // 初始化订单
    }

    private function OrderInit(){
        $this->transactionData = $this->CreatePayOrder();
        $this->checkpaytype($this->transactionData['pay_type'] , $this->action_name);

        $this->LoadChannel(); // 加载入口使用的支付通道
        $this->InsertStatus = M('Transaction')->add($this->transactionData);
        $this->CreateOrder = self::getparameter($this->transactionData);

        if($this->transactionData['pay_type'] == 'weixinGzh_pay'){
            $this->transactionData['user_id'] = I('get.user_id');
        }

        $Paydata = array(
            'transactionData' => $this->transactionData,
            'get_data' => $this->CreateOrder,
            'payName' => $this->channelInfo['payName'],
            'mch_id' => $this->channelInfo['mch_id'],
            'PayChannel_MethodName' => $this->channelInfo['mch_channel'],
        ); // 这个数组是存准备调用的通道方法名 商户号 、 订单号 、 订单信息 、 金额等等

        $this->payData = $Paydata;
        $this->CrearePayObj = new \Api\Controller\CreatePayController(); // 方便在传构造方法中传参数
    }


    private function checkpaytype($pay_type,$action_name){
        if($action_name != $pay_type){
            exit(json_encode(array('error' => 8 , 'msg' => '支付类型不正确'),JSON_UNESCAPED_UNICODE));
        }
        return true;
    }


    /* 加载各个入口使用的渠道 */
    private function LoadChannel(){
        $Table = M("payconfig");
        $passageway_group = $this->transactionData['passageway_group']; // 用于多条通道的区分

        // 通道使用的优先级顺序
        $tiaojian = array(
            array('effective_merchant' => $this->transactionData['merchant'] , 'passageway_price' => array('GT' , 0) , 'passageway_group' => $passageway_group), // 指定商户号，并且商户号满足金额
            array('effective_merchant' => $this->transactionData['merchant'] , 'passageway_price' => array('ELT' , 0) , 'passageway_group' => $passageway_group), // 指定商户号的通道，并且没有指定金额的通道
            array('effective_merchant' => 0 , 'passageway_price' => array('GT' , 0) , 'passageway_group' => $passageway_group),  // 所有商户号，并且金额满足金额
            array('effective_merchant' => 0 , 'passageway_price' => array('ELT' , 0) , 'passageway_group' => $passageway_group) // 所有商户号金额不满足，寻找默认通道。并且该通道是没有指定金额的
        );

        // 需求：多条通道指定了金额，需要匹配最高的那一条

        $keyName = strtolower($this->action_name);
        foreach ($tiaojian as $value){
            $rachel = $Table->field("passageway_price," . $this->action_name)->where($value)->select();
            // 寻找高金额的通道
            foreach($rachel as $value1){
                if($value1['passageway_price'] <= $this->transactionData['paymoney']){
                    $tongdao = $value1;
                }
            }

            $rachel = $tongdao;
            if($rachel){
                // 找到通道，还要检查请求的金额是否可以使用
                if($this->action_name == 'weixinGzh_pay')   $keyName = 'weixingzh_pay';
                if($rachel['passageway_price'] > 0 && ((float)$this->transactionData['paymoney'] < (float)$rachel['passageway_price'])) { // 请求的金额不满足这条通道的使用，那就继续找下一条通道
                    continue;
                }

                $this->channelInfo = json_decode($rachel[$keyName] , true);
                // 判断一下是否要寻找默认通道
                $isContinueMerchant = M('payconfig')->where(array('effective_merchant' => $this->transactionData['merchant'] , 'passageway_group' => $passageway_group))->getField('continue_merchant');
                if($isContinueMerchant == 0){
                    if(empty($this->channelInfo['mch_channel'])) continue; // 虽然是满足金额，但是如果找不到这个支付方式的对应通道，则继续往下寻找
                }
                break;
            }
        }

        if($this->channelInfo['mch_channel'] == '') exit('管理员尚未分配可用通道');

    }

    private function CreatePayOrder(){
        $data = I('request.','','strip_tags,htmlentities');
        $merchantData =  $this->CheckBaseparam($data);
        $Banktype = BankType($data['banktype']); // 可能会有异常输出
        $transactionData = array(
            'out_trade_no' => $data['ordernumber'],
            'systrade_no'  => randNumber(),
            'merchant'     => $merchantData['merchant_id'],
            'passageway_group' => (I('request.passageway_group' , '' , 'intval') == 0 || I('request.passageway_group' , '' , 'intval') == "") ? 0 : I('request.passageway_group' , '' , 'intval'),
            'paymoney'     => $data['paymoney'],
            'order_time'   => $data['order_time'],
            'notify_url'   => str_replace('&amp;' , '&' , urldecode($data['notify_url'])),
            'callback_url' => isset($data['href_backurl']) ? $data['href_backurl'] : '',
            'pay_status'   => 0,
            'pay_type'     => $Banktype,
            'ipaddress'    => $data['ClientIp'],
            'create_begtime' => time(),
            'update_begtime' => ''
        );
        if($transactionData['pay_type'] == 'bank_pay') {
            return $this->BankSelect($transactionData , $data['user_id'] , $merchantData['merchant_id']); // 如果是网银支付的话则显示网银支付选择页面
        }
        // 不确认页面直接返回支付数据
        return $transactionData;
    }

    private function BankSelect($transactionData , $user_id , $merchant_id){
        // 针对银行选择界面
        $expire = 180; // 页面过期时间
        if((time() - intval($transactionData['order_time'])) > $expire){
            exit(json_encode(array('error' => 9 , 'msg' => '订单超时'),JSON_UNESCAPED_UNICODE));
        }
        // 选择银行支付
        $BankType = strip_tags($_POST['BankType']);
        if(IS_POST && !empty($BankType)){
            $transactionData  = json_decode(\Think\Crypt\Driver\Think::decrypt($_POST['i'] , C('encryptKey')),true);
            $transactionData['BankType'] = $BankType;
            return $transactionData;
        }
        $voucherConf = array(
            'merchant_id' => $merchant_id,
            'user_id'  => $user_id,
            'generateTime' => time()
        );
        $voucherConfSign = strtoupper(md5($voucherConf['merchant_id'] . $voucherConf['user_id'] . $voucherConf['generateTime'] . C('SignKey')));
        $voucherConf['sign'] = $voucherConfSign;
        // 第一次页面显示银行
        $BankTab = M('bankcardnum');
        $OneWhere = array('mch_id' => $merchant_id, 'user_id'  => $user_id);
        $oneCount = $BankTab->where($OneWhere)->count();
        if($oneCount > 0){
            // 用户保存过银行卡号
            $OneBankNum = $BankTab->field('bankCode')->where($OneWhere)->getField('bankCode'); // 取一个银行进行第一次的默认显示
            $newarr = array_merge($OneWhere ,array('bankCode' => $OneBankNum));
            $this->assign(
                array(
                    'OneBankDatas' => $BankTab->field('bankaccount')->where($newarr)->select(),
                    'bankcode' => $OneBankNum
                ));
        }
        $CXvoucher = \Think\Crypt\Driver\Think::encrypt(json_encode($voucherConf), C('encryptKey') , $expire);
        $Self = \Think\Crypt\Driver\Think::encrypt(json_encode($transactionData), C('encryptKey') , $expire);
        $this->assign('payInfo' , $Self); // 支付信息加密保留在表单
        $this->assign('CXvoucher' , $CXvoucher); // 添加银行卡的凭证
        $this->assign('money' , $transactionData['paymoney']);
        $this->display('selectBank');
        exit;
    }

    //////////// 四种支付方式入口方法，方便代码扩展
    public function alipay_pay(){
        // 支付宝入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/alipay_pay/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);
        }else{
            exit('未知错误');
        }
    }

    public function weixinGzh_pay(){
        // 微信入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/weixinGzh_pay/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);

        }else{
            exit('未知错误');
        }
    }

    public function qq_pay(){
        // qq支付入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/qq_pay/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);
        }else{
            exit('未知错误');
        }
    }

    public function jd_pay(){
        // 京东钱包入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/jd_pay/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);
        }else{
            exit('未知错误');
        }
    }

    public function WeixinScancode(){
        // 微信扫码入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/WeixinScancode/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);
        }else{
            exit('未知错误');
        }
    }

    public function bank_Pay(){
        // 微信入口。
        if($this->InsertStatus) {
            \Think\Log::write(json_encode($this->transactionData), 'INFO', '', LOG_PATH . "Api/CreateOrder/bank_pay/" . date('Y-m-d') . ".log");
            $this->CrearePayObj->InitPassageway($this->payData);
        }else{
            exit('未知错误');
        }
    }

}